package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

func BasicGetData(c *gin.Context) {
	name := c.Query("name") //获取URL中 ?后面的参数
	//返回字符串类型数据
	//c.String(http.StatusOK,"欢迎您：%s",name)

	//获取登录的用户信息
	//loginUserName := c.MustGet(gin.AuthUserKey).(string)
	//fmt.Println("loginUserName", loginUserName)

	//返回json数据
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK, //状态
		"data": "欢迎您：" + name, //数据
		//"msg":  "当前登录用户：" + loginUserName,
	})
}

func BasicPostData(c *gin.Context) {
	name := c.DefaultPostForm("name", "Gin") //获取body中的数据（form形式）
	fmt.Println("name:", name)
	form, err := c.GetPostForm("name") //获取body中的数据（form形式）
	fmt.Println("form:", form, err)

	//耗时任务
	//同步执行三个任务
	//for i := 0; i < 3; i++ {
	//	longTimeCost(c, i)
	//}
	//异步执行三个任务
	for i := 0; i < 3; i++ {
		go longTimeCost(c, i)
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": "欢迎您：" + name,
	})
}

func longTimeCost(cp *gin.Context, i int) {
	println("第" + strconv.Itoa(i) + "个任务开始执行：" + cp.Request.URL.Path)
	time.Sleep(time.Second * 5)
	println("第" + strconv.Itoa(i) + "个任务执行完毕")
}

func BasicCurlData(c *gin.Context) {
	url := "https://profile-avatar.csdnimg.cn/2334e87504d344588c50c0125c4e39da_rxbook.jpg!1"
	response, err := http.Get(url)
	if err != nil || response.StatusCode != http.StatusOK {
		c.Status(http.StatusServiceUnavailable)
		return
	}
	body := response.Body
	contentLength := response.ContentLength
	contentType := response.Header.Get("Content-Type")
	//数据写入响应体
	c.DataFromReader(http.StatusOK, contentLength, contentType, body, nil)
}
